Page({
  data: {
    id: null,
    name: '',
    relation: '',
    phone: '',
    isSaving: false
  },

  onLoad(options) {
    if (options.id) {
      this.loadContact(options.id);
    }
  },

  loadContact(id) {
    wx.cloud.callFunction({
      name: 'getEmergencyContact',
      data: { id },
      success: (res) => {
        const contact = res.result.data;
        this.setData({
          id: contact._id,
          name: contact.name,
          relation: contact.relation,
          phone: contact.phone
        });
      }
    });
  },

  onNameChange(e) {
    this.setData({ name: e.detail.value });
  },

  onRelationChange(e) {
    this.setData({ relation: e.detail.value });
  },

  onPhoneChange(e) {
    this.setData({ phone: e.detail.value });
  },

  onSave() {
    if (!this.data.name || !this.data.phone) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    this.setData({ isSaving: true });

    const data = {
      name: this.data.name,
      relation: this.data.relation,
      phone: this.data.phone
    };

    const action = this.data.id ? 'updateEmergencyContact' : 'addEmergencyContact';
    if (this.data.id) {
      data.id = this.data.id;
    }

    wx.cloud.callFunction({
      name: action,
      data,
      success: () => {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      },
      fail: () => {
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        });
      },
      complete: () => {
        this.setData({ isSaving: false });
      }
    });
  }
});